<template>
		<div style="width: 35%">
				<el-row>
						<el-input prefix-icon="el-icon-search" style="width: 100%;margin-bottom: 15px" v-model="filterText"
																:clearable="true"></el-input>
				</el-row>
				<el-row>
						<el-tree
										v-loading="treeLoading"
										class="filter-tree"
										:data="departmentData"
										:props="defaultProps"
										:filter-node-method="filterNode"
										:expand-on-click-node="false"
										ref="tree">
								<span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
														class="treeBtn"
														type="primary"
														size="mini"
														@click="()=>showAddDialog(node,data)">
            添加部门
          </el-button>
          <el-button
														class="treeBtn"
														type="danger"
														size="mini"
														@click="()=>deleteDepartment(node,data)">
            删除部门
          </el-button>
        </span>
      </span>
						</el-tree>
				</el-row>
				<el-dialog title="添加部门" :visible.sync="dialogFormVisible" width="25%" :before-close="resetDialogForm">
						<el-form :model="dialogForm" label-width="100px" :rules="dialogFormRule" ref="departmentForm">
								<el-row>
										<el-form-item label="上级部门" prop="parentid">
												<el-select v-model="dialogForm.parentid" style="width: 100%" :clearable="true">
														<el-option v-for="(item,index) in departmentSelectData" :key="index" :label="item.name"
																									:value="item.id"></el-option>
												</el-select>
										</el-form-item>
										<el-form-item label="部门名称" style="width: 100%" prop="name">
												<el-input v-model="dialogForm.name" autocomplete="off" placeholder="请输入部门名称"
																						@keydown.enter.native="saveDepartmentDialog"></el-input>
										</el-form-item>
								</el-row>
						</el-form>
						<div slot="footer" class="dialog-footer">
								<el-button @click="resetDialogForm">取 消</el-button>
								<el-button type="primary" @click="saveDepartmentDialog">确 定</el-button>
						</div>
				</el-dialog>
		</div>
</template>

<script>
export default {
		name: "DepartmentManager",
		data() {
				return {
						filterText: '',
						departmentData: [],
						treeLoading: false,
						defaultProps: {
								label: 'name',
								children: 'children'
						},
						departmentSelectData: [],
						dialogFormVisible: false,
						dialogForm: {
								parentid: '',
								name: ''
						},
						dialogFormRule: {
								parentid: [{required: true, message: '请至少选择一个上级部门', trigger: 'change'}],
								name: [{required: true, message: '请输入部门名称', trigger: 'blur'},
										{min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur'}
								]
						}
				}
		},
		mounted() {
				this.init()
		},

		methods: {
				init() {
						this.listAllDepartmentsWithChildren();
						this.listAllDepartmentName();
				},
				filterNode(value, data) {
						// data表示 departmentData 数组中的一个元素,
						// filterNode方法会递归过滤这个数组里面的每个元素,
						// 判断data.name元素中有没有对应的value值的(data.?取决于用哪个key作为过滤值)
						if (!value) return true;
						return data.name.indexOf(value) !== -1;
				},
				// 获取树状结构部门数据
				listAllDepartmentsWithChildren() {
						this.treeLoading = true
						setTimeout(() => {
								this.$get("/system/basic/department/listAllDepartmentsWithChildren").then(res => {
										this.treeLoading = false
										const {data} = res;
										this.departmentData = data;
								})
						}, 200)
				},
				// 获取所有的部门名称
				listAllDepartmentName() {
						this.$get("/system/basic/department/listAllDepartmentName").then(res => {
								const {data} = res;
								this.departmentSelectData = data;
						})
				},

				// 展示对话框
				showAddDialog(node, data) {
						this.dialogFormVisible = true;
						this.dialogForm.parentid = data.id;
				},

				// 保存部门
				saveDepartmentDialog() {
						this.$refs.departmentForm.validate((valid) => {
								if (valid) {
										this.$post("/system/basic/department/savaDepartment", this.dialogForm).then(res => {
												this.appendNewDeptToDept(this.departmentData, res.data)
												this.resetDialogForm()
										})
								}
						})
				},

				// 追加部门到原来的部门数组中
				appendNewDeptToDept(oldDept, newDept) {
						for (let i = 0; i < oldDept.length; i++) {
								let oDept = oldDept[i]
								if (oDept.id === newDept.parentid) {
										oldDept[i].children.push(newDept)
										return
								} else {
										this.appendNewDeptToDept(oldDept[i].children, newDept)
								}
						}
				},

				// 重置表单数据
				resetDialogForm() {
						this.dialogFormVisible = false;
						this.$refs.departmentForm.resetFields()
				},

				// 删除部门
				deleteDepartment(node, data) {
						if (!node.isLeaf) {
								this.$message.error("当前部门下还有子部门,无法删除!!")
								return false;
						}
						this.$confirm(`确认删除【${data.name}】?`, '警告').then(res => {
								this.$del("/system/basic/department/deleteDepartment", data.id).then(res => {
										const {code} = res;
										if (code === 200) {
												this.spliceDept(data.id, this.departmentData)
										}
								})
						}).catch(error => {
								this.$message.info("取消删除")
						})
				},

				// 删除原departmentData 数组中的数据
				spliceDept(id, deptData) {
						for (let i = 0; i < deptData.length; i++) {
								let dept = deptData[i]
								if (dept.id === id) {
										deptData.splice(i, 1)
										return false;
								} else {
										this.spliceDept(id, dept.children)
								}
						}
				}
		},
		watch: {
				filterText(val) {
						this.$refs.tree.filter(val);
				}
		},
}
</script>

<style lang="less" scoped>
.custom-tree-node {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 14px;
		padding-right: 8px;

		.treeBtn {
				padding: 2px;
		}

}
</style>
